const {
    router,
    VbenResult,
    querySql,
    queryOne
} = require('../connect');
const md5 = require('../utils/md5');
const boom = require('boom');
const moment = require('moment');
const {
    body,
    validationResult
} = require('express-validator');
const {
    CODE_ERROR,
    CODE_SUCCESS,
    TYPE_SUCCESS,
    TYPE_FAIL,
} = require('../utils/constant');

// var request = require('request');
var querystring = require('querystring');

const { setToken } = require('../token/token');
// const { setString } = require('../redis/redis');

router.post('/vben/login', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        let {
            username,
            password
        } = req.body;
        password = md5(password);
        const query = `select * from vben_user where username='${username}' and password='${password}'`;
        querySql(query).then(user => {
            if (!user || user.length === 0) {
                res.json(new VbenResult({
                    code: CODE_ERROR,
                    message: '用户名或密码错误',
                    result: null,
                    type: TYPE_FAIL
                }))
            } else {
                const userInfo = user[0]
                setToken(userInfo.username, userInfo.userId).then(token => {
                    res.json(new VbenResult({
                        code: CODE_SUCCESS,
                        message: '登录成功',
                        result: {
                            ...userInfo,
                            token
                        },
                        type: TYPE_SUCCESS
                    }))
                })



            }
        })

    }

})


// 通过用户名查询用户信息
function findUser(username) {
    const query = `select username from vben_user where username='${username}'`;
    return queryOne(query);
}


router.post('/vben/register', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        let {
            realName,
            username,
            introduction,
            password,
            homePath,
        } = req.body;

        findUser(username).then(data => {
            if (data) {
                res.json(new VbenResult({
                    code: CODE_ERROR,
                    message: '用户已存在',
                    result: null,
                    type: TYPE_FAIL
                }))
            } else {
                password = md5(password);
                const createTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
                const query = `insert into vben_user(realName, username, introduction, password, homePath, createTime) 
                                values('${realName}', '${username}', '${introduction}', '${password}', '${homePath}', '${createTime}')`;
                querySql(query).then(result => {
                    if (!result || result.lenght === 0) {
                        res.json(new VbenResult({
                            code: CODE_ERROR,
                            message: '注册失败',
                            result: null,
                            type: TYPE_FAIL
                        }))
                    } else {
                        const queryUser = `select * from vben_user where username='${username}' and password='${password}'`;
                        querySql(queryUser).then(user => {
                            const userInfo = user[0]
                            setToken(userInfo.username, userInfo.userId).then(token => {
                                res.json(new VbenResult({
                                    code: CODE_SUCCESS,
                                    message: '注册成功',
                                    result: {
                                        ...userInfo,
                                        token
                                    },
                                    type: TYPE_SUCCESS
                                }))
                            })

                        })
                    }
                })
            }
        })
    }

})

router.get('/vben/getUserInfo', (req, res) => {
    let params = req.query
    let sql = ''
    if (params.userId) {
        sql = `select * from vben_user where userId=${params.userId}`
    } else {
        sql = 'select * from vben_user'
    }

    let where_value = [params.userId]
    querySql(sql).then(result => {
        res.json(new VbenResult({
            code: CODE_SUCCESS,
            message: '查询成功',
            result,
            type: TYPE_SUCCESS
        }))
    })
})

router.get('/vben/logout', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        res.json(new VbenResult({
            code: CODE_SUCCESS,
            message: '退出成功',
            result: null,
            type: TYPE_SUCCESS
        }))
    }
})


// router.post('/vben/sendMsg', (req, res, next) => {
//     const err = validationResult(req);
//     // 如果验证出错，error不为空[]
//     if (!err.isEmpty()) {
//         // 获取错误信息
//         const [{
//             msg
//             // @ts-ignore
//         }] = err.errors;
//         // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
//         next(boom.badRequest(msg));
//     } else {
//         const {
//             mobile
//         } = req.body;

//         const code = Math.random().toString().slice(-6)
//         console.log("=======code====", code)

//         var queryData = querystring.stringify({
//             "mobile": mobile,  // 接收短信的用户手机号码
//             "tpl_id": "150261",  // 您申请的短信模板ID，根据实际情况修改
//             "tpl_value": `#code#=${code}`,  // 您设置的模板变量，根据实际情况修改；无变量则为空
//             "key": "35da7ad1b81223d4bdc49e5f11990e16",  // 应用APPKEY(应用详细页查询)
//         });

//         var queryUrl = 'http://v.juhe.cn/sms/send';

//         request.post({ url: queryUrl, form: queryData }, function (error, response, body) {
//             if (!error && response.statusCode == 200) {
//                 var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
//                 if (jsonObj) {
//                     var errorCode = jsonObj.error_code;
//                     var reason = jsonObj.reason;
//                     if (errorCode == 0) {
//                         // 请求发送成功，可根据实际逻辑修改
//                         var sid = jsonObj.result.sid;

//                         res.json(new VbenResult({
//                             code: CODE_SUCCESS,
//                             message: '发送成功',
//                             result: sid,
//                             type: TYPE_SUCCESS
//                         }))

//                         // setString(mobile, code, 60 * 5)
//                     } else {
//                         // 请求失败
//                         res.json(new VbenResult({
//                             code: CODE_ERROR,
//                             message: '发送失败',
//                             result: errorCode + ' ' + reason,
//                             type: TYPE_FAIL
//                         }))
//                     }
//                 } else {
//                     // 可能网络异常等问题请求失败，可根据实际逻辑修改
//                     console.log('解析JSON异常');
//                     res.json(new VbenResult({
//                         code: CODE_ERROR,
//                         message: '发送失败',
//                         result: '解析JSON异常',
//                         type: TYPE_FAIL
//                     }))
//                 }
//             } else {
//                 // 可能网络异常等问题请求失败，可根据实际逻辑修改
//                 res.json(new VbenResult({
//                     code: CODE_ERROR,
//                     message: '发送失败',
//                     result: '请求异常' + error + response.statusCode,
//                     type: TYPE_FAIL
//                 }))
//             }
//         })
//     }
// })


// router.post('/vben/test', (req, res) => {
//     const code = Math.random().toString().slice(-6)
//     const {
//         mobile
//     } = req.body;

//     setString(mobile, code, 60 * 5)

// })

module.exports = router;